import { Request, Response } from 'express';
import { Audio } from '../models/Audio';
import multer from 'multer';
import path from 'path';
import fs from 'fs';

// 配置 multer 存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = 'uploads/audio';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

// 文件过滤器
const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  if (file.mimetype.startsWith('audio/')) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传音频文件'));
  }
};

export const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024 // 10MB
  }
});

// 获取所有音频
export const getAudios = async (req: Request, res: Response) => {
  try {
    const audios = await Audio.find();
    res.json(audios);
  } catch (error) {
    res.status(500).json({ message: '获取音频列表失败', error });
  }
};

// 获取单个音频
export const getAudio = async (req: Request, res: Response) => {
  try {
    const audio = await Audio.findById(req.params.id);
    if (!audio) {
      return res.status(404).json({ message: '音频不存在' });
    }
    res.json(audio);
  } catch (error) {
    res.status(500).json({ message: '获取音频失败', error });
  }
};

// 上传音频
export const uploadAudio = async (req: Request, res: Response) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: '请选择要上传的音频文件' });
    }

    const audio = new Audio({
      title: req.body.title,
      description: req.body.description,
      filePath: req.file.path,
      duration: req.body.duration,
      category: req.body.category
    });

    await audio.save();
    res.status(201).json({
      message: '上传音频成功',
      audio
    });
  } catch (error) {
    res.status(500).json({ message: '上传音频失败', error });
  }
};

// 更新音频信息
export const updateAudio = async (req: Request, res: Response) => {
  try {
    const audio = await Audio.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    );
    
    if (!audio) {
      return res.status(404).json({ message: '音频不存在' });
    }
    
    res.json({
      message: '更新音频成功',
      audio
    });
  } catch (error) {
    res.status(500).json({ message: '更新音频失败', error });
  }
};

// 删除音频
export const deleteAudio = async (req: Request, res: Response) => {
  try {
    const audio = await Audio.findById(req.params.id);
    
    if (!audio) {
      return res.status(404).json({ message: '音频不存在' });
    }

    // 删除文件
    if (fs.existsSync(audio.filePath)) {
      fs.unlinkSync(audio.filePath);
    }

    await audio.deleteOne();
    res.json({ message: '删除音频成功' });
  } catch (error) {
    res.status(500).json({ message: '删除音频失败', error });
  }
}; 